package com.mdlib.helper.presenter;

import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.ljlib.core.app.AppManager;
import com.mdlib.helper.api.DataManager;
import com.mdlib.helper.api.network.ApiErrorCode;
import com.mdlib.helper.api.network.RxHelper;
import com.mdlib.helper.api.network.RxSubscribe;
import com.mdlib.helper.common.MDConstant;
import com.mdlib.helper.event.LoginEvent;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.model.AppModel;
import com.mdlib.helper.model.BaseResult;
import com.mdlib.helper.model.UserModel;
import com.mdlib.helper.model.entity.AccountInfo;
import com.mdlib.helper.model.entity.AuthUser;
import com.mdlib.helper.model.entity.LoginRunInfo;
import com.mdlib.helper.model.entity.UserEntity;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by librabin on 16/11/24.
 */

public class LoginHelper {

    private static void postLoginFail(String msg) {
        EventBus.getDefault().post(new LoginEvent(MDConstant.STATE_FAIL, msg));
    }

    private static void postLoginSucc(String msg) {
        EventBus.getDefault().post(new LoginEvent(MDConstant.STATE_SUCC, msg));
    }


    public static void doAuthLogin(final AuthUser authUser) {
        DataManager.getInstance().getAccountApi()
                .doAuthLogin(authUser.getUid(), authUser.getNickName(), authUser.getAvatar(),
                        authUser.getSex(),AppModel.getInstance().getPushToken(), MDConstant.CLIENT_TYPE)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<BaseResult<AccountInfo>, Observable<BaseResult<UserEntity>>>() {
                    @Override
                    public Observable<BaseResult<UserEntity>> call(BaseResult<AccountInfo> accountInfoBaseResult) {
                        AccountModel.getInstance().setLoginType(MDConstant.ACCOUNT_TYPE_AUTH);
                        AccountModel.getInstance().setThirdType(authUser.getAuthType());
                        AccountModel.getInstance().setThirdUid(authUser.getUid());
                        AccountModel.getInstance().setSessionId(accountInfoBaseResult.data.sessionId);
                        AccountModel.getInstance().writeToCache();
                        return DataManager.getInstance().getUserApi().fetchUserInfo();
                    }
                })
                .compose(RxHelper.<UserEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<UserEntity>() {
                    @Override
                    protected void onSucc(UserEntity userEntity) {
                        UserModel.getInstance().setUserInfo(userEntity);
                        UserModel.getInstance().writeToCache();
                        postLoginSucc("登录成功");
                    }

                    @Override
                    protected void onFail(String msg) {
                        postLoginFail(msg);
                    }
                });
    }

    public static void doLogin(final String loginName, final String loginPwd) {
        DataManager.getInstance().getAccountApi()
                .doLogin(loginName, loginPwd, MDConstant.CLIENT_TYPE, AppModel.getInstance().getPushToken(),
                        AccountModel.getInstance().getRoleType()
                )
                .compose(RxHelper.<AccountInfo>defaultHandleResult())
                .subscribe(new RxSubscribe<AccountInfo>() {
                    @Override
                    protected void onSucc(AccountInfo accountInfo) {
                        AccountModel.getInstance().setSessionId(accountInfo.sessionId);
                        AccountModel.getInstance().setLoginName(loginName);
                        AccountModel.getInstance().setLoginPwd(loginPwd);
                        AccountModel.getInstance().setLoginType(MDConstant.ACCOUNT_TYPE_DEFAULT);
                        AccountModel.getInstance().writeToCache();
                        getFetchUserInfo();
                    }

                    @Override
                    protected void onFail(String msg) {

                    }

                    @Override
                    protected void onFail(int code, String msg, String data) {
                        if (code == ApiErrorCode.ERROR_RUN_AUDIT) {
                            Gson gson = new Gson();
                            LoginRunInfo loginRunInfo = gson.fromJson(data, LoginRunInfo.class);
                            AccountModel.getInstance().setSessionId(loginRunInfo.getSesseinId());
                            if (loginRunInfo.getRunCode().equals("0")) {
                                UserModel.getInstance().setPhone(loginName);
                                final Activity activity = AppManager.getAppManager().currentActivity();
                                UIHelper.showRun(activity);
                            } else if (loginRunInfo.getRunCode().equals("1")) {
                                final FragmentActivity runActivity = (FragmentActivity) AppManager.getAppManager().currentActivity();
                                UIHelper.showLoginRun(runActivity);
                            } else if (loginRunInfo.getRunCode().equals("2")) {
                                postLoginFail("审核成功！");
                            } else if (loginRunInfo.getRunCode().equals("3")) {
                                postLoginFail("审核失败！");
                            } else if (loginRunInfo.getRunCode().equals("4")) {
                                postLoginFail("您的跑客账号已被停用！");
                            }
                        } else {
                            postLoginFail(msg);
                        }


                    }
                });


//        DataManager.getInstance().getAccountApi()
//                .doLogin(loginName, loginPwd, MDConstant.CLIENT_TYPE, AccountModel.getInstance().getRoleType())
//                .subscribeOn(Schedulers.io())
//                .flatMap(new Func1<BaseResult<AccountInfo>, Observable<BaseResult<UserEntity>>>() {
//                    @Override
//                    public Observable<BaseResult<UserEntity>> call(BaseResult<AccountInfo> accountInfoBaseResult) {
//                        AccountModel.getInstance().setSessionId(accountInfoBaseResult.data.sessionId);
//                        AccountModel.getInstance().setLoginName(loginName);
//                        AccountModel.getInstance().setLoginPwd(loginPwd);
//                        AccountModel.getInstance().setLoginType(MDConstant.ACCOUNT_TYPE_DEFAULT);
//                        AccountModel.getInstance().writeToCache();
//                        return DataManager.getInstance().getUserApi().fetchUserInfo();
//                    }
//                })
//                .compose(RxHelper.<UserEntity>defaultHandleResult())
//                .subscribe(new RxSubscribe<UserEntity>() {
//                    @Override
//                    protected void onSucc(UserEntity userEntity) {
//                        UserModel.getInstance().setUserInfo(userEntity);
//                        UserModel.getInstance().writeToCache();
//                        postLoginSucc("登录成功");
//                    }
//
//                    @Override
//                    protected void onFail(String msg) {
//                        postLoginFail(msg);
//                    }
//
//                    @Override
//                    protected void onFail(int code, String msg, String data) {
//                        super.onFail(code, msg, data);
//                        LogUtil.e("DATA: " + data);
//                    }
//                });


    }

    private static void getFetchUserInfo() {
        DataManager.getInstance().getUserApi().fetchUserInfo()
                .compose(RxHelper.<UserEntity>defaultHandleResult())
                .subscribe(new RxSubscribe<UserEntity>() {
                    @Override
                    protected void onSucc(UserEntity userEntity) {
                        UserModel.getInstance().setUserInfo(userEntity);
                        UserModel.getInstance().writeToCache();
                        postLoginSucc("登录成功");
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.showToast(msg);
                    }
                });
    }


    public static void doMsgLogin(final String phoneNum, String phoneCode) {

        DataManager.getInstance().getAccountApi()
                .doMsgLogin(phoneNum, phoneCode, MDConstant.CLIENT_TYPE,AppModel.getInstance().getPushToken(), AccountModel.getInstance().getRoleType())
                .compose(RxHelper.<AccountInfo>defaultHandleResult())
                .subscribe(new RxSubscribe<AccountInfo>() {
                    @Override
                    protected void onSucc(AccountInfo accountInfo) {
                        AccountModel.getInstance().setSessionId(accountInfo.sessionId);
                        AccountModel.getInstance().setLoginType(MDConstant.ACCOUNT_TYPE_MSG);
                        AccountModel.getInstance().writeToCache();
                        getFetchUserInfo();
                    }

                    @Override
                    protected void onFail(String msg) {

                    }

                    @Override
                    protected void onFail(int code, String msg, String data) {
                        if (code == ApiErrorCode.ERROR_RUN_AUDIT) {
                            Gson gson = new Gson();
                            LoginRunInfo loginRunInfo = gson.fromJson(data, LoginRunInfo.class);
                            AccountModel.getInstance().setSessionId(loginRunInfo.getSesseinId());
                            if (loginRunInfo.getRunCode().equals("0")) {
                                UserModel.getInstance().setPhone(phoneNum);
                                final Activity activity = AppManager.getAppManager().currentActivity();
                                UIHelper.showRun(activity);
                            } else if (loginRunInfo.getRunCode().equals("1")) {
                                final FragmentActivity runActivity = (FragmentActivity) AppManager.getAppManager().currentActivity();
                                UIHelper.showLoginRun(runActivity);
                            } else if (loginRunInfo.getRunCode().equals("2")) {
                                postLoginFail("审核成功！");
                            } else if (loginRunInfo.getRunCode().equals("3")) {
                                postLoginFail("审核失败！");
                            } else if (loginRunInfo.getRunCode().equals("4")) {
                                postLoginFail("您的跑客账号已被停用！");
                            }
                        } else {
                            postLoginFail(msg);
                        }
                    }
                });


//        DataManager.getInstance().getAccountApi()
//                .doMsgLogin(phoneNum, phoneCode, MDConstant.CLIENT_TYPE, AccountModel.getInstance().getRoleType())
//                .subscribeOn(Schedulers.io())
//                .flatMap(new Func1<BaseResult<AccountInfo>, Observable<BaseResult<UserEntity>>>() {
//                    @Override
//                    public Observable<BaseResult<UserEntity>> call(BaseResult<AccountInfo> accountInfoBaseResult) {
//                        AccountModel.getInstance().setSessionId(accountInfoBaseResult.data.sessionId);
//                        AccountModel.getInstance().setLoginType(MDConstant.ACCOUNT_TYPE_MSG);
//                        AccountModel.getInstance().writeToCache();
//                        return DataManager.getInstance().getUserApi().fetchUserInfo();
//                    }
//                })
//                .compose(RxHelper.<UserEntity>defaultHandleResult())
//                .subscribe(new RxSubscribe<UserEntity>() {
//                    @Override
//                    protected void onSucc(UserEntity userEntity) {
//                        UserModel.getInstance().setUserInfo(userEntity);
//                        UserModel.getInstance().writeToCache();
//                        postLoginSucc("登录成功");
//                    }
//
//                    @Override
//                    protected void onFail(String msg) {
//                        postLoginFail(msg);
//                    }
//
//                    @Override
//                    protected void onFail(int code, String msg, String data) {
//                        super.onFail(code, msg, data);
//
//                    }
//                });

    }


}
